package com.zline.foodraise.js;

import android.content.Context;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;

import cn.pedant.SafeWebViewBridge.InjectedChromeClient;

/**
 * Created by heshantao on 15/8/4.
 * 封装webView 设置
 */
public class MyWebViewSetting {
    private static final String LOG_TAG = MyWebViewSetting.class.getSimpleName();
    WebView wv;
    WebSettings mWebSettings;
    Context cxt;
    NetworkUtil networkUtil;

    public MyWebViewSetting(WebView webView, Context context) {
        super();
        this.wv = webView;
        this.cxt = context;
        networkUtil = new NetworkUtil();
    }

    public void setWebView() {
        wv.requestFocus();//能够获得焦点
        WebSettings settings = wv.getSettings();
        //图片等页面加载完后在加载
        if (Build.VERSION.SDK_INT >= 19) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }

        //缓存策略：设置没有网络时从缓存中读取
        if (!networkUtil.isNetworkAvailable()) {
            settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        } else {
            LUtil.i(LOG_TAG, "_________有网路________");
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        }
        //支持缩放
        settings.setSupportZoom(true);
        //出现缩放工具
        settings.setBuiltInZoomControls(true);
        //扩大比例的缩放
        settings.setUseWideViewPort(true);
        // 自适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        //设置有缓存并且设置大小
        settings.setAppCacheMaxSize(1024 * 1024 * 4);
        String appCachePath = cxt.getApplicationContext().getDir(Constant.CACHE, Context.MODE_PRIVATE).getPath();
        //LUtil.i(LOG_TAG, "_________appCachePath________"+appCachePath);
        settings.setAppCachePath(appCachePath);
        settings.setAppCacheEnabled(true);
        //可以读取文件缓存
        settings.setAllowFileAccess(true);
        //启动数据库
        settings.setDatabaseEnabled(true);
        String dir = cxt.getApplicationContext().getDir(Constant.DATABASE, Context.MODE_PRIVATE).getPath();
        //LUtil.i(LOG_TAG, "_________dir________"+dir);
        //启动定位
        settings.setGeolocationEnabled(true);
        //设置定位的数据库路径
        settings.setGeolocationDatabasePath(dir);
        settings.setJavaScriptEnabled(true);// 允许js操作
        settings.setJavaScriptCanOpenWindowsAutomatically(true);// 允许JS 弹出窗口
        settings.setDomStorageEnabled(true);//开启本地存储

        wv.setWebChromeClient(new CustomChromClient("CC", HostJSScope.class));

        wv.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && wv != null && wv.canGoBack()) {
                    wv.goBack();
                    return true;//return true表示这个事件已经被消费，不会再向上传播
                }
                return false;
            }
        });
    }


    public class CustomChromClient extends InjectedChromeClient {

        public CustomChromClient(String injectedName, Class injectedCls) {
            super(injectedName, injectedCls);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            LUtil.i(LOG_TAG, "_________alert________" + message);
            openAlerDialog(message);
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        //添加位置权限
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
    }


    void openAlerDialog(String msg) {
        new MaterialDialog.Builder(cxt)
                .content(msg)
                .positiveText(R.string.ok)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        dialog.dismiss();
                    }
                })
                .show();
    }


}
